package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock {

    private StringRedisTemplate redisTemplate;

    private static String  KEY_PREFIX = "lock:";

    private String name;

    public SimpleRedisLock(StringRedisTemplate redisTemplate, String name) {
        this.redisTemplate = redisTemplate;
        this.name = name;
    }


    @Override
    public boolean tryLock(long expireTime) {
        long threadId = Thread.currentThread().getId();
        Boolean success = redisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, threadId + "", expireTime, TimeUnit.MINUTES);
        if (success) return true;
        return false;
    }

    @Override
    public void unlock() {
        Long id = UserHolder.getUser().getId();
        redisTemplate.delete(KEY_PREFIX + name);
    }
}
